package com.cumt.mybatisstudy;

import com.cumt.mybatisstudy.entity.User;
import com.cumt.mybatisstudy.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.Reader;

/**
 * Created by caicf on 2017/1/3.
 */
public class MybatisStart {
    private static final Logger log = LoggerFactory.getLogger(MybatisStart.class);

    @Test
    public void queryTest() throws IOException {
        Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession session = sqlSessionFactory.openSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        User user = userMapper.findById(1);
        log.info("name= {} ; age= {}", user.getName(), user.getAge());
    }

    @Test
    public void jdbccQQuyueryTest() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/mybatis_study";
        Connection conn = DriverManager.getConnection(url, "root", "123456");
        PreparedStatement statement = null;
        ResultSet rs = null;
        if (conn != null) {
            System.out.println("get conn");
            String sql = "select id,name from user where id=?";
            statement = conn.prepareStatement(sql);
            statement.setInt(1, 1);
            statement.execute();

            rs = statement.getResultSet();
            if (rs != null) {
                System.out.println("get rs");
                User user = new User();
                for (; rs.next(); ) {
                    user.setId(rs.getInt("id"));
                    user.setName(rs.getString("name"));
                    //...
                }
            System.out.println(JSON.toJSONString(user));
            }
        }
        rs.close();
        conn.close();
        statement.close();
    }
}
